package bamin.com.bamindaijia.Activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.aiton.administrator.shane_library.shane.utils.ACache;
import com.aiton.administrator.shane_library.shane.utils.GsonUtils;
import com.aiton.administrator.shane_library.shane.utils.UILUtils;
import com.aiton.administrator.shane_library.shane.widget.AvatarImageView;
import com.aiton.administrator.shane_library.shane.widget.WheelView;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.nostra13.universalimageloader.core.ImageLoader;

import java.io.File;
import java.io.FileNotFoundException;

import bamin.com.bamindaijia.R;
import bamin.com.bamindaijia.constant.Constant;
import bamin.com.bamindaijia.model.User;
import cz.msebera.android.httpclient.Header;

public class MineActivity extends ZjbBaseActivity implements View.OnClickListener {

    private PopupWindow mPopupWindow;
    private User mUser;
    private boolean IsLogin;
    private AvatarImageView mImg_Avatar;
    private Uri photoUri;
    private final int PIC_FROM＿LOCALPHOTO = 0;
    private final int PIC_FROM_CAMERA = 1;
    private String mImage;
    private String mPhoneNum;
    private ACache aCache;
    private TextView mTv_Name;
    private PopupWindow mChoosePopupWindow;
    private TextView mTv_User_Sex;
    private WheelView wheelview;
    private TextView mTv_User_Age;
    private String imgUrl;
    private User.DatasBean datas;
    private TextView mTv_QianMing;
    private TextView mTv_User_Phone;
    private String name;
    private TextView mTv_User_carID;
    private TextView mTv_User_emergency;
    private int sex = 0;
    private ImageView mMan;
    private ImageView mWoman;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mine);

        init();
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
                != PackageManager.PERMISSION_GRANTED) {
            //申请WRITE_EXTERNAL_STORAGE权限
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA},
                    Constant.PERMISSION.CAMERA);//自定义的code
        }
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void initViews() {
        User.DatasBean datas = mUser.getDatas();
        if (datas != null) {
            mImage = datas.getImage();
            mPhoneNum = datas.getPhone();
            name = datas.getName();
            sex =  datas.getSex();
            String licensePlate = datas.getLicensePlate();
            String importantPerson = datas.getImportantPerson();


            String phone = datas.getPhone();
            int id = datas.getId();
            if (TextUtils.isEmpty(mImage)) {
                String Path = "/upload/" + mPhoneNum + "upload.jpeg";
                File pictureFile = new File(Environment.getExternalStorageDirectory(), Path);
                if (pictureFile.exists()) {
                    Uri uri = Uri.fromFile(pictureFile);
                    Bitmap bitmap = decodeUriAsBitmap(uri);
                    mImg_Avatar.setImageBitmap(bitmap);
                    Log.e("checkLogin", "本地图片存在");
                } else {
                    Log.e("checkLogin", "本地图片不存在");
                    mImg_Avatar.setImageResource(R.mipmap.ic_avatar);
                }
            } else {
                if (mImage != null) {
                    Log.e("checkLogin", "图片URL" + mImage);
                    UILUtils.displayImageNoAnim(mImage, mImg_Avatar);
                }
            }
//            if (sex != null && !TextUtils.isEmpty(sex)) {
//                mTv_User_Sex.setText(sex);
//
//            }
//            if (age != null && !TextUtils.isEmpty(age)) {
//                mTv_User_Age.setText(age);
//
//            }
            if (name != null && !TextUtils.isEmpty(name)) {
                mTv_Name.setText(name);
            }

            if (!TextUtils.isEmpty(phone)) {
                mImg_Avatar.setFileName(phone + "upload");
                mTv_User_Phone.setText(phone);
            }
            if(!TextUtils.isEmpty(licensePlate)){
                mTv_User_carID.setText(licensePlate);
            }
            if(!TextUtils.isEmpty(importantPerson)){
                mTv_User_emergency.setText(importantPerson);
            }
            if(sex == 1){
                mMan.setVisibility(View.VISIBLE);
                mWoman.setVisibility(View.GONE);
            }else {
                mMan.setVisibility(View.GONE);
                mWoman.setVisibility(View.VISIBLE);
            }
        }
    }


    @Override
    protected void setListeners() {
        findViewById(R.id.imageView_back).setOnClickListener(this);
        findViewById(R.id.rela_user_sex).setOnClickListener(this);
        findViewById(R.id.rela_user_name).setOnClickListener(this);
        findViewById(R.id.rela_uesr_age).setOnClickListener(this);
        findViewById(R.id.rela_user_qianming).setOnClickListener(this);
        findViewById(R.id.rela_user_carID).setOnClickListener(this);
        findViewById(R.id.rela_user_emergency).setOnClickListener(this);

        //头像控件监听
        mImg_Avatar.setAfterCropListener(new AvatarImageView.AfterCropListener() {
            @Override
            public void afterCrop(Bitmap photo) {
                Toast.makeText(MineActivity.this, "设置新的头像成功", Toast.LENGTH_SHORT).show();

                Log.e("MainActivity", "afterCrop: --->>" + mImg_Avatar.getFileName());
                postFile(mImg_Avatar.getFileName());
            }
        });
    }

    @Override
    protected void initSP() {
        aCache = ACache.get(this);
        mUser = (User) aCache.getAsObject(Constant.ACACHE.USER);

        datas = mUser.getDatas();
        imgUrl = datas.getImage();


        if (mUser == null) {

            Log.e("getSP ", "user为空");
        } else {

            Log.e("getSP ", "存储的电话号码" + mUser.getDatas().getPhone());
            Log.e("getSP ", "user状态" + mUser.getStatus());
        }
    }

    @Override
    protected void initIntent() {

    }

    @Override
    protected void findID() {
        mImg_Avatar = (AvatarImageView) findViewById(R.id.imageView_touXiang);
        mTv_Name = (TextView) findViewById(R.id.tv_user_name);
        mTv_User_Sex = (TextView) findViewById(R.id.tv_user_sex);
        mTv_User_Age = (TextView) findViewById(R.id.tv_user_age);
        mTv_QianMing = (TextView) findViewById(R.id.tv_user_qianming);
        mTv_User_Phone = (TextView) findViewById(R.id.tv_user_phone);
        mTv_User_carID = (TextView) findViewById(R.id.tv_user_carID);
        mTv_User_emergency = (TextView) findViewById(R.id.tv_user_emergency);
        mMan = (ImageView) findViewById(R.id.man);
        mWoman = (ImageView) findViewById(R.id.woman);
    }


    @Override
    public void onClick(View v) {
        Intent intent = new Intent();
        String userName = mTv_Name.getText().toString().trim();
        String carID = mTv_User_carID.getText().toString().trim();
        String emergency = mTv_User_emergency.getText().toString().trim();
        String image = mUser.getDatas().getImage();
        if (userName.equals("请填写姓名")) {
            userName = "";
        }
        if (carID.equals("请填写车牌号")) {
            carID = "";
        }
        if (emergency.equals("请填写紧急联系人")) {
            emergency = "";
        }
        switch (v.getId()) {
            case R.id.imageView_back:
//                intent.putExtra(Constant.INTENT_KEY.USER_NAME, userName);
//                intent.putExtra(Constant.INTENT_KEY.USER_AVATAR, image);
//                setResult(Constant.REQUEST_RESULT_CODE.USER_INFO, intent);
                finishTo();
                break;

            case R.id.rela_user_name://姓名
                intent.setClass(this, ChangeNameActivity.class);
                intent.putExtra(Constant.INTENT_KEY.CHANGE_NAME, userName);
                intent.putExtra(Constant.INTENT_KEY.ADD_INFO_TYPE, Constant.TYPE.CHANGE_NAME);

                startActivityForResultTo(intent, Constant.REQUEST_RESULT_CODE.CHANGE_NAEM);

                break;
            case R.id.rela_user_carID://车牌号
                intent.setClass(this, ChangeNameActivity.class);
                intent.putExtra(Constant.INTENT_KEY.CAR_ID, carID);
                intent.putExtra(Constant.INTENT_KEY.ADD_INFO_TYPE, Constant.TYPE.CAR_ID);
                startActivityForResultTo(intent, Constant.REQUEST_RESULT_CODE.CAR_ID);
                break;
            case R.id.rela_user_emergency://紧急联系人
                intent.setClass(this, ChangeNameActivity.class);
                intent.putExtra(Constant.INTENT_KEY.EMERGENCY, emergency);
                intent.putExtra(Constant.INTENT_KEY.ADD_INFO_TYPE, Constant.TYPE.EMERGENCY);
                startActivityForResultTo(intent, Constant.REQUEST_RESULT_CODE.EMERGENCY);
                break;
            case R.id.rela_user_sex://性别
                intent.setClass(this, ChangeNameActivity.class);
                intent.putExtra(Constant.INTENT_KEY.SEX, sex);
                intent.putExtra(Constant.INTENT_KEY.ADD_INFO_TYPE, Constant.TYPE.SEX);
                startActivityForResultTo(intent, Constant.REQUEST_RESULT_CODE.SEX);
                break;

        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        pushUserInfo();

    }

    /**
     * 上传用户信息
     */
    private void pushUserInfo() {
        String name = mTv_Name.getText().toString().trim();
        String carId = mTv_User_carID.getText().toString().trim();
        String emergency = mTv_User_emergency.getText().toString().trim();
//        String age = mTv_User_Age.getText().toString().trim();
        boolean isChange = false;
        if (!(name.equals("请填写姓名") || TextUtils.equals(name,mUser.getDatas().getName())) ){

            isChange = true;
        }
        if (!(name.equals("请填写车牌号") || TextUtils.equals(carId,mUser.getDatas().getLicensePlate()))) {
            isChange = true;
        }
        if (!(name.equals("请填写紧急联系人") || TextUtils.equals(emergency,mUser.getDatas().getImportantPerson()))) {
            isChange = true;
        }
        if(!(sex == mUser.getDatas().getSex())){
            isChange = true;
        }
        if(isChange){

            String url = Constant.Url.USER_INFO;
            AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
            RequestParams params = new RequestParams();
            params.put("id", mUser.getDatas().getId());
            params.put("name", name);
            params.put("phone", mUser.getDatas().getPhone());
            params.put("sex", sex);
            params.put("licensePlate", carId);
            params.put("importantPerson", emergency);

            asyncHttpClient.post(url, params, new AsyncHttpResponseHandler() {
                @Override
                public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                    String s = new String(responseBody);
                    Log.e("MineActivity", "用户信息: --->>" + s);

                    try {
                        mUser = GsonUtils.parseJSON(s, User.class);
                        if (mUser.getStatus() == 0) {
                            aCache.clear();
                            aCache.put(Constant.ACACHE.USER, mUser, 30 * ACache.TIME_DAY);
                            mUser = (User) aCache.getAsObject(Constant.ACACHE.USER);

                            sendUserBroadcase();

                            Log.e("MineActivity", "用户名字: --->>" + mUser.getDatas().getName());

                        }
                    } catch (Exception e) {
                        Toast.makeText(MineActivity.this, "数据解析失败", Toast.LENGTH_SHORT).show();
                    }
                }

                @Override
                public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                    Toast.makeText(MineActivity.this, "用户信息保存失败", Toast.LENGTH_SHORT).show();
                }
            });
        }

        //保存用户信息在本地


        Log.e("MineActivity", "onStop:imgUrl>>" + imgUrl);
        Log.e("MineActivity", "onStop:Name>>" + name);
//        Log.e("MineActivity", "onStop:imgUrl>>" + age);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (requestCode == Constant.REQUEST_RESULT_CODE.CHANGE_NAEM && resultCode == Constant.REQUEST_RESULT_CODE.CHANGE_NAEM) {  //改变姓名

            String name = data.getStringExtra(Constant.INTENT_KEY.CHANGE_NAME);
            Log.e("MineActivity", "name: --->>" + name);
            mTv_Name.setText(name);
        } else if (requestCode == Constant.REQUEST_RESULT_CODE.CAR_ID && resultCode == Constant.REQUEST_RESULT_CODE.CAR_ID) {//车牌号
            String carId = data.getStringExtra(Constant.INTENT_KEY.CAR_ID);
            Log.e("MineActivity", "carId: --->>" + carId);
            // TODO: 2016/9/5 车牌号，还未保存到服务器
            mTv_User_carID.setText(carId);
        }else if(requestCode == Constant.REQUEST_RESULT_CODE.EMERGENCY && resultCode == Constant.REQUEST_RESULT_CODE.EMERGENCY){//紧急联系人
            String emergency = data.getStringExtra(Constant.INTENT_KEY.EMERGENCY);
            Log.e("MineActivity", "emergency: --->>" + emergency);
            // TODO: 2016/9/5 紧急联系人号码，还未保存到服务器
            mTv_User_emergency.setText(emergency);
        }else if(requestCode == Constant.REQUEST_RESULT_CODE.SEX && resultCode == Constant.REQUEST_RESULT_CODE.SEX){//紧急联系人
            sex = data.getIntExtra(Constant.INTENT_KEY.SEX,1);
            Log.e("MineActivity", "emergency: --->>" + sex);
            // TODO: 2016/9/5 性别，还未保存到服务器
            if(sex == 1){
                mMan.setVisibility(View.VISIBLE);
                mWoman.setVisibility(View.GONE);
            }else {
                mMan.setVisibility(View.GONE);
                mWoman.setVisibility(View.VISIBLE);
            }
        }

        //在拍照、选取照片、裁剪Activity结束后，调用的方法
        if (mImg_Avatar != null) {
            mImg_Avatar.onActivityResult(requestCode, resultCode, data);
        }

    }

    /**
     * 上传图片
     *
     * @param uploadFile
     */
    public void postFile(Uri uploadFile) {
        String path = uploadFile.getPath();
        Log.e("postFile", "path" + path);
        File file = new File(path);
        String actionUrl = Constant.Url.CUSTOMERIMAGE;
        if (file.exists() && file.length() > 0) {
            RequestParams params = new RequestParams();
            params.put("customer_id", mUser.getDatas().getId());
            Log.e("postFile", "用户ID" + mUser.getDatas().getId());
            try {
                params.put("data", file);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
            asyncHttpClient.post(actionUrl, params, new AsyncHttpResponseHandler() {

                @Override
                public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                    Log.e("onSuccess: ", "---> " + new String(responseBody));
                    try {

                        imgUrl = new String(responseBody);
                        datas.setImage(imgUrl);
                        mUser.setDatas(datas);
                        aCache.clear();
                        aCache.put(Constant.ACACHE.USER, mUser, 30 * ACache.TIME_DAY);
                        mUser = (User) aCache.getAsObject(Constant.ACACHE.USER);

                        sendUserBroadcase();

                        Log.e("MineActivity", "imgUrl:>>" + imgUrl);

                    } catch (Exception e) {

                    }

                }

                @Override
                public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                    Log.e("onFailure", "失败");
                }
            });
        } else {
            Toast.makeText(this, "文件不存在", Toast.LENGTH_LONG).show();
        }
        ImageLoader.getInstance().clearDiskCache();
    }

    private void sendUserBroadcase() {
        Intent intent = new Intent(Constant.BROADCASTCODE.USER);
        intent.putExtra(Constant.INTENT_KEY.USER,mUser);
        sendBroadcast(intent);
    }

    private Bitmap decodeUriAsBitmap(Uri uri) {
        Bitmap bitmap = null;
        try {
            bitmap = BitmapFactory.decodeStream(this.getContentResolver().openInputStream(uri));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        }
        return bitmap;
    }

}
